// 推荐经纪人页面脚本
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM已加载完成');
    
    try {
        // 加载经纪人列表
        loadRecommendedAgents();
        
        // 初始化搜索功能
        initSearch();
        
        // 初始化筛选标签
        initFilterTags();
        
        console.log('所有初始化函数已执行');
    } catch (error) {
        console.error('初始化过程中发生错误:', error);
        alert('初始化失败: ' + error.message);
    }
});

// 加载推荐经纪人列表
function loadRecommendedAgents() {
    console.log('开始加载推荐经纪人');
    
    try {
        // 获取推荐经纪人数据
        const agentsData = getAgentsData();
        console.log('获取到经纪人数据:', agentsData.length, '条记录');
        
        // 渲染经纪人列表
        renderAgentsList(agentsData);
    } catch (error) {
        console.error('加载推荐经纪人失败:', error);
        showErrorMessage('加载经纪人数据失败，请刷新页面重试');
    }
}

// 获取经纪人数据（模拟数据）
function getAgentsData() {
    console.log('获取经纪人数据');
    // 模拟的经纪人数据
    return [
        {
            id: 'agent1',
            name: '张明',
            title: '前BAT高级HR',
            avatar: 'https://images.pexels.com/photos/3760263/pexels-photo-3760263.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.9,
            reviewCount: 243,
            level: '金牌',
            verified: true,
            industry: '互联网',
            tags: ['简历优化', '面试辅导', '互联网行业'],
            about: '8年互联网HR经验，曾在BAT担任招聘负责人，擅长简历优化和面试指导，帮助200+学生成功入职一线互联网公司。',
            stats: {
                students: '200+',
                satisfactionRate: '98%',
                salaryIncrease: '30%'
            }
        },
        {
            id: 'agent2',
            name: '王静',
            title: '资深金融顾问',
            avatar: 'https://images.pexels.com/photos/5393594/pexels-photo-5393594.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 5.0,
            reviewCount: 156,
            level: '金牌',
            verified: true,
            industry: '金融',
            tags: ['职业规划', '投行求职', '金融行业'],
            about: '毕业于哈佛商学院，曾在高盛工作10年，擅长投行求职指导和职业规划，帮助150+学生成功入职国内外顶级金融机构。',
            stats: {
                students: '150+',
                satisfactionRate: '100%',
                salaryIncrease: '45%'
            }
        },
        {
            id: 'agent3',
            name: '李华',
            title: '金融行业导师',
            avatar: 'https://images.pexels.com/photos/3785104/pexels-photo-3785104.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.8,
            reviewCount: 120,
            level: '银牌',
            verified: true,
            industry: '金融',
            tags: ['职业规划', '求职策略', '金融行业'],
            about: '曾在四大会计师事务所工作6年，现任某大型券商高管，擅长金融行业求职指导和职业发展规划。',
            stats: {
                students: '120+',
                satisfactionRate: '95%',
                salaryIncrease: '25%'
            }
        },
        {
            id: 'agent4',
            name: '陈进',
            title: '互联网产品专家',
            avatar: 'https://images.pexels.com/photos/614810/pexels-photo-614810.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.7,
            reviewCount: 98,
            level: '银牌',
            verified: true,
            industry: '互联网',
            tags: ['产品设计', 'PM求职', '互联网行业'],
            about: '10年互联网产品经验，曾在阿里、腾讯担任产品负责人，擅长产品思维培养和求职规划，帮助100+学生成功转行互联网产品。',
            stats: {
                students: '100+',
                satisfactionRate: '96%',
                salaryIncrease: '35%'
            }
        },
        {
            id: 'agent5',
            name: '刘芳',
            title: '教育行业顾问',
            avatar: 'https://images.pexels.com/photos/762020/pexels-photo-762020.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.6,
            reviewCount: 87,
            level: '银牌',
            verified: false,
            industry: '教育',
            tags: ['教师发展', '职业规划', '教育行业'],
            about: '拥有15年教育行业经验，曾任国际学校教学总监，现为多家教育机构提供职业发展咨询。帮助100+教育工作者实现职业晋升和转型。',
            stats: {
                students: '100+',
                satisfactionRate: '92%',
                salaryIncrease: '20%'
            }
        },
        {
            id: 'agent6',
            name: '赵健',
            title: 'IT技术专家',
            avatar: 'https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.8,
            reviewCount: 76,
            level: '银牌',
            verified: true,
            industry: '互联网',
            tags: ['技术提升', '算法指导', '架构设计'],
            about: '12年技术开发经验，曾在字节跳动担任技术总监，擅长算法指导和技术面试辅导，帮助80+学生成功入职一线互联网公司。',
            stats: {
                students: '80+',
                satisfactionRate: '97%',
                salaryIncrease: '40%'
            }
        },
        {
            id: 'agent7',
            name: '林小雨',
            title: '医疗健康顾问',
            avatar: 'https://images.pexels.com/photos/1181686/pexels-photo-1181686.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.5,
            reviewCount: 65,
            level: '铜牌',
            verified: false,
            industry: '医疗',
            tags: ['医疗行业', '职业规划', '求职辅导'],
            about: '8年医疗行业人力资源经验，曾在多家三甲医院和医疗机构担任HR总监，擅长医疗行业职业规划和求职辅导。',
            stats: {
                students: '60+',
                satisfactionRate: '90%',
                salaryIncrease: '18%'
            }
        },
        {
            id: 'agent8',
            name: '周扬',
            title: '咨询行业导师',
            avatar: 'https://images.pexels.com/photos/2379005/pexels-photo-2379005.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.9,
            reviewCount: 58,
            level: '银牌',
            verified: true,
            industry: '咨询',
            tags: ['管理咨询', '求职策略', '案例分析'],
            about: '曾在麦肯锡工作5年，现为某咨询公司合伙人，擅长案例分析和求职指导，帮助50+学生成功入职顶级咨询公司。',
            stats: {
                students: '50+',
                satisfactionRate: '98%',
                salaryIncrease: '50%'
            }
        },
        {
            id: 'agent9',
            name: '张雪',
            title: '设计行业专家',
            avatar: 'https://images.pexels.com/photos/774909/pexels-photo-774909.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.7,
            reviewCount: 48,
            level: '铜牌',
            verified: false,
            industry: '设计',
            tags: ['UI设计', '作品集', '面试技巧'],
            about: '10年设计行业经验，曾在腾讯、阿里等公司担任设计负责人，擅长作品集优化和设计思维培养，帮助40+学生成功入职一线互联网公司。',
            stats: {
                students: '40+',
                satisfactionRate: '95%',
                salaryIncrease: '30%'
            }
        }
    ];
}

// 渲染经纪人列表
function renderAgentsList(agents) {
    console.log('开始渲染经纪人列表');
    const contentContainer = document.getElementById('agents-content');
    
    if (!contentContainer) {
        console.error('找不到内容容器元素: agents-content');
        return;
    }
    
    // 清空加载指示器
    contentContainer.innerHTML = '';
    
    if (agents && agents.length > 0) {
        console.log('渲染', agents.length, '个经纪人');
        // 创建页面内容
        let content = `
            <div class="section-title">
                <span>全部推荐 (${agents.length})</span>
                <div class="sort-options">
                    <span>综合排序</span>
                    <i class="bi bi-chevron-down"></i>
                </div>
            </div>

            <div class="agent-list" id="agent-list">
                ${agents.map(agent => `
                    <div class="agent-card fade-in" data-industry="${agent.industry}">
                        <div class="agent-header">
                            <img src="${agent.avatar}" alt="${agent.name}" class="agent-avatar" onerror="this.src='../images/default-avatar.jpg'">
                            <div class="agent-info">
                                <div class="agent-name">
                                    ${agent.name} ${agent.verified ? '<i class="bi bi-patch-check-fill"></i>' : ''}
                                </div>
                                <div class="agent-title">${agent.title}</div>
                                <div class="agent-rating">
                                    <div class="rating-stars">
                                        ${Array(Math.floor(agent.rating)).fill('<i class="bi bi-star-fill"></i>').join('')}
                                        ${agent.rating % 1 > 0 ? '<i class="bi bi-star-half"></i>' : ''}
                                    </div>
                                    <span class="rating-score">${agent.rating}</span>
                                    <span class="rating-count">(${agent.reviewCount}条评价)</span>
                                </div>
                            </div>
                        </div>
                        <div class="agent-body">
                            <div class="agent-tags">
                                ${agent.tags.map(tag => `<span class="agent-tag">${tag}</span>`).join('')}
                            </div>
                            <div class="agent-desc">${agent.about}</div>
                            <div class="agent-stats">
                                <div class="agent-stat">
                                    <div class="stat-value">${agent.stats.students}</div>
                                    <div class="stat-label">服务学员</div>
                                </div>
                                <div class="agent-stat">
                                    <div class="stat-value">${agent.stats.satisfactionRate}</div>
                                    <div class="stat-label">好评率</div>
                                </div>
                                <div class="agent-stat">
                                    <div class="stat-value">${agent.stats.salaryIncrease}</div>
                                    <div class="stat-label">平均提薪</div>
                                </div>
                            </div>
                            <div class="agent-actions">
                                <button class="action-btn detail-btn" data-agent-id="${agent.id}">查看详情</button>
                                <button class="action-btn consult-btn" data-agent-id="${agent.id}">咨询</button>
                            </div>
                        </div>
                    </div>
                `).join('')}
            </div>
        `;
        
        // 添加内容到页面
        contentContainer.innerHTML = content;
        console.log('经纪人列表渲染完成');
        
        // 初始化经纪人卡片交互
        initAgentCards();
    } else {
        console.log('没有经纪人数据，显示空状态');
        // 显示空状态
        showEmptyState();
    }
}

// 初始化经纪人卡片交互
function initAgentCards() {
    const agentCards = document.querySelectorAll('.agent-card');
    
    agentCards.forEach(card => {
        // 查看详情按钮
        const detailBtn = card.querySelector('.detail-btn');
        if (detailBtn) {
            detailBtn.addEventListener('click', function() {
                const agentId = this.getAttribute('data-agent-id');
                if (agentId) {
                    window.location.href = `agent-detail.html?id=${agentId}`;
                }
            });
        }
        
        // 咨询按钮
        const consultBtn = card.querySelector('.consult-btn');
        if (consultBtn) {
            consultBtn.addEventListener('click', function() {
                const agentId = this.getAttribute('data-agent-id');
                if (agentId) {
                    // 在真实应用中，这里应该跳转到咨询页面或弹出联系表单
                    showMessage('预约成功，稍后会有客服联系您');
                    
                    // 修改按钮状态
                    this.innerHTML = '已预约';
                    this.disabled = true;
                    this.style.backgroundColor = '#999';
                }
            });
        }
    });
}

// 初始化搜索功能
function initSearch() {
    const searchInput = document.getElementById('search-input');
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const query = this.value.trim().toLowerCase();
            
            // 获取所有经纪人数据
            const allAgents = getAgentsData();
            
            // 根据搜索关键词筛选经纪人
            const filteredAgents = allAgents.filter(agent => {
                return agent.name.toLowerCase().includes(query) || 
                       agent.title.toLowerCase().includes(query) || 
                       agent.industry.toLowerCase().includes(query) || 
                       agent.tags.some(tag => tag.toLowerCase().includes(query)) || 
                       agent.about.toLowerCase().includes(query);
            });
            
            // 渲染筛选后的经纪人列表
            renderAgentsList(filteredAgents);
            
            // 重置筛选标签
            resetFilterTags();
        });
    }
}

// 初始化筛选标签
function initFilterTags() {
    const filterTags = document.querySelectorAll('.filter-tag');
    
    filterTags.forEach(tag => {
        tag.addEventListener('click', function() {
            // 更新标签状态
            filterTags.forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            
            // 获取筛选条件
            const filter = this.getAttribute('data-filter');
            
            // 获取所有经纪人数据
            const allAgents = getAgentsData();
            
            // 根据筛选条件过滤经纪人
            let filteredAgents;
            if (filter === 'all') {
                filteredAgents = allAgents;
            } else {
                filteredAgents = allAgents.filter(agent => agent.industry === filter || agent.tags.includes(filter));
            }
            
            // 渲染筛选后的经纪人列表
            renderAgentsList(filteredAgents);
            
            // 清空搜索输入框
            const searchInput = document.getElementById('search-input');
            if (searchInput) {
                searchInput.value = '';
            }
        });
    });
}

// 重置筛选标签
function resetFilterTags() {
    const filterTags = document.querySelectorAll('.filter-tag');
    filterTags.forEach(tag => {
        tag.classList.remove('active');
        if (tag.getAttribute('data-filter') === 'all') {
            tag.classList.add('active');
        }
    });
}

// 显示空状态
function showEmptyState() {
    const contentContainer = document.getElementById('agents-content');
    contentContainer.innerHTML = `
        <div class="empty-state">
            <i class="bi bi-search"></i>
            <h3>未找到匹配的经纪人</h3>
            <p>尝试使用其他关键词或筛选条件</p>
        </div>
    `;
}

// 显示消息提示
function showMessage(message) {
    // 创建消息元素
    const messageElement = document.createElement('div');
    messageElement.style.position = 'fixed';
    messageElement.style.bottom = '20px';
    messageElement.style.left = '50%';
    messageElement.style.transform = 'translateX(-50%)';
    messageElement.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    messageElement.style.color = 'white';
    messageElement.style.padding = '10px 20px';
    messageElement.style.borderRadius = '20px';
    messageElement.style.fontSize = '14px';
    messageElement.style.zIndex = '1000';
    messageElement.textContent = message;
    
    // 添加到页面
    document.body.appendChild(messageElement);
    
    // 3秒后移除
    setTimeout(() => {
        document.body.removeChild(messageElement);
    }, 3000);
}

// 显示错误信息
function showErrorMessage(message) {
    const contentContainer = document.getElementById('agents-content');
    if (contentContainer) {
        contentContainer.innerHTML = `
            <div style="text-align: center; padding: 40px 20px;">
                <i class="bi bi-exclamation-circle" style="font-size: 50px; color: #ff5c5c; margin-bottom: 15px;"></i>
                <h3 style="font-size: 16px; color: #333; margin-bottom: 10px;">加载失败</h3>
                <p style="font-size: 14px; color: #666;">${message}</p>
                <button onclick="location.reload()" style="margin-top: 20px; padding: 8px 20px; background-color: #4e6ef2; color: white; border: none; border-radius: 4px; cursor: pointer;">重新加载</button>
            </div>
        `;
    }
} 